<?php
declare (strict_types=1);

namespace app\user\logic\user;

use app\common\exception\LogicException;
use app\common\helper\util\SnowFlake;
use app\common\model\payment\PaymentOrder as PO;
use app\common\model\payment\PaymentOrderItem as POI;
use app\common\model\ProductType;
use app\user\model\user\Vip as VipModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 账户会员接口类
 */
class Vip extends VipModel
{
    /**
     * Vip基础信息
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-23
     */
    public function basic(): array
    {
        // 用户会员有效期
        $return['expire_time'] = app(VipUser::class)->userVipExpire();
        $return['vip_status']  = $return['expire_time'] ? ($return['expire_time'] > time() ? 1 : 2) : 0;
        // 类型
        try {
            $return['vip'] = $this->select();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            $return['vip'] = [];
        }
        // 支付方式
        // $payway = SystemConfig::get('system.package.payment', [], request()->mhm_id);
        // array_unshift($payway, 'lcnpay');
        // $return['payway']  = $payway;
        // 余额
        // if (in_array('lcnpay', $return['payway'])) {
        //     $return['balance'] = app(Balance::class)->userBalance();
        // }

        return $return;
    }

    /**
     * 购买会员
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-25
     */
    public function buy($param)
    {
        // 验证数据
        $this->getValidate()->scene('buy')->failException()->check($param);
        $vip_id = $param['vip_id'];
        $mid    = request()->mid;
        // 会员信息
        $data = $this->findOrFail($vip_id);
        // 当前会员时效
        $vip_user    = app(VipUser::class)->mid($mid)->findOrEmpty();
        $today0Time  = strtotime(date("Y-m-d"), time()) + 86400;
        $expire_time = $vip_user->isEmpty() ? $today0Time : max($vip_user->expire_time, $today0Time);
        $expire_time += bcadd($data->days . '', $data->give_days . '') * 86400;
        // 生成订单
        return $this->createOrder($data, $expire_time);
    }

    /**
     * 创建订单方法
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-25
     */
    protected function createOrder($data, $expire_time)
    {
        $from = strtolower(request()->device_type);
        $this->startTrans();
        try {
            // 用户ID
            $mid = request()->mid;
            $PD  = app(SnowFlake::class)->createPD();
            $PI  = app(SnowFlake::class)->createPI();
            // 主订单
            $order = app(PO::class)::create([
                'order_no'   => $PD,
                'user_id'    => $mid,
                'from'       => $from,
                'mhm_id'     => request()->user->mhm_id,
                'payment'    => $data->price,
                'status'     => '10',
                'close_time' => time() + 30 * 60,
            ]);

            if ($order->isEmpty()) throw new LogicException('订单生成失败', '主订单生成失败');
            // 子订单
            $order_item = app(POI::class)::create([
                'order_no'        => $PD,
                'order_sub_no'    => $PI,
                'user_id'         => $mid,
                'from'            => $from,
                'mhm_id'          => request()->user->mhm_id,
                'product_id'      => $data['id'],
                'product_type_id' => ProductType::getProductIdByKey('vip'),
                'payment'         => $data['price'],
                'original_price'  => $data['scribing_price'],
                'expire_time'     => $expire_time,
                'ext_data'        => json_encode(['vip_title' => $data->title]),
            ]);
            if ($order_item->isEmpty()) throw new LogicException('订单生成失败', '子订单生成失败');

            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            throw new LogicException($e->getMessage());
        }
        unset($order->id);
        return $order;
    }

    public function userVipLog()
    {
        return app(POI::class)->alias('poi')->join('payment_order po', 'poi.order_no=po.order_no AND po.status=20')->field('poi.order_no,poi.ext_data,poi.expire_time,poi.payment')->where('poi.user_id', request()->mid)->proType(ProductType::getProductIdByKey('vip'))->with(['transaction_time'])->paginate($this->getListRows());
    }

}
